package com.littlebee.storychild.common.json;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 作者：liaoyong on 2016/7/27 16:31
 * 邮箱：liaoyong@tuliu.com
 * 描述：JSON数据的解析
 */
public class JsonTools {
    /**
     * 反序列化泛型集合
     * <p/>
     * jsonobject
     *
     * @param genericType Class<T> 实体类类型
     * @return <T> 封装了实体类对象的<T>
     * @throws JSONException
     */
    @SuppressWarnings("unchecked")
    public static <T> T jsonParseCollection(JSONObject jsonObject,
                                            Class<T> genericType) throws JSONException {
        Object o = jsonObject;
        if (o == null) {
            return null;
        }

        if (o instanceof JSONObject) {
            T object = JsonHelper.parseObjectWithAnno((JSONObject) o,
                    genericType);
            return object;
        }
        return null;
    }

    /**
     * 反序列化泛型集合
     * <p/>
     * JSONArray
     *
     * @param genericType Class<T> 实体类类型
     * @return List<T> 封装了实体类对象的List<T>
     * @throws JSONException
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> jsonParseCollection(JSONArray jsonArray,
                                                  Class<T> genericType) throws JSONException {
        Object o = jsonArray;
        if (o == null) {
            return new ArrayList<T>();
        }

        if (o instanceof JSONArray) {
            return (List<T>) JsonHelper.parseCollectionWithAnnotation((JSONArray) o,
                    List.class,
                    genericType);
        }
        return new ArrayList<T>();
    }

    /**
     * Json 转成 Map<>
     *
     * @return
     */
    public static Map<String, Object> getMapForJson(JSONObject jsonObject)
    {
        try
        {

            Iterator<String> keyIter = jsonObject.keys();
            String key;
            Object value;
            Map<String, Object> valueMap = new HashMap<String, Object>();
            while (keyIter.hasNext())
            {
                key = keyIter.next();
                value = jsonObject.get(key);
                valueMap.put(key, value);
            }
            return valueMap;
        }
        catch (Exception e)
        {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
}
